//
//  SYDMySettingViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/9.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDMySettingViewController.h"
#import "XBSettingCell.h"
#import "XBSettingItemModel.h"
#import "XBSettingSectionModel.h"
#import "SYDAboutViewController.h"
#import "SYDResetTheWordController.h"
#import "SYDRestPayMentWordController.h"
#import "SYDFeedbackController.h"
#import "YMSetupViewController.h"

@interface SYDMySettingViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataList;
@property (nonatomic,strong) NSArray  *sectionArray; /**< section模型数组*/
@property(nonatomic,strong)UIButton *loginOutBtn;
@property(nonatomic,strong)UserAccountModel *userAccountModel;

@end

@implementation SYDMySettingViewController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取个人账号信息
    [self getMineAccountFromServer];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationBar.title = @"设置";
    [self navigationBarHandle];
    [self setupSections];
}
#pragma mark---获取个人账号信息
-(void)getMineAccountFromServer{
    WEAKSELF
    [[SYDNetwork shareTool]getMineAcountWithUserId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                UserAccountModel *model = [UserAccountModel mj_objectWithKeyValues:responseObject[@"obj"]];
                weakSelf.userAccountModel = model;
                
                // refresh tableview
                [weakSelf setupSections];
            }
        } @catch (NSException *exception) {
            NSLog(@"exception:%@",exception.description);
        } @finally {
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma - mark setup
- (void)setupSections
{
    WEAKSELF
    //************************************section1
    XBSettingItemModel *item1 = [[XBSettingItemModel alloc]init];
    item1.funcName = @"重置登录密码";
    item1.executeCode = ^{
        SYDResetTheWordController *resetVc = [[SYDResetTheWordController alloc]init];
        resetVc.userAccountModel = weakSelf.userAccountModel;
        [weakSelf.navigationController pushViewController:resetVc animated:YES];
    };
    item1.accessoryType = XBSettingAccessoryTypeDisclosureIndicator;
    
    XBSettingSectionModel *section1 = [[XBSettingSectionModel alloc]init];
    section1.sectionHeaderName = @"账号";
    section1.sectionHeaderBgColor = SUB_TITLE_COLOR;
    section1.sectionHeaderHeight = 44;
    section1.itemArray = @[item1];
    
    //************************************section2
    XBSettingItemModel *item2 = [[XBSettingItemModel alloc]init];
    item2.funcName = @"重置支付密码";
    item2.executeCode = ^{
        if (![weakSelf.userAccountModel.payCode isEqualToString:@""]) {
            SYDRestPayMentWordController *restVc = [[SYDRestPayMentWordController alloc]init];
            restVc.userAccountModel = weakSelf.userAccountModel;
            [weakSelf.navigationController pushViewController:restVc animated:YES];
        } else {//需要设置支付密码
            // 验证成功
            SYDSetThepaymentController *setVc = [[SYDSetThepaymentController alloc]init];
            [weakSelf.navigationController pushViewController:setVc animated:YES];
        }
    };
    item2.accessoryType = XBSettingAccessoryTypeDisclosureIndicator;
    
    XBSettingItemModel *item3 = [[XBSettingItemModel alloc]init];
    item3.funcName = @"找回支付密码";
    item3.executeCode = ^{
      SYDRetrievePayPasswordController *payVc = [[SYDRetrievePayPasswordController alloc]init];
        payVc.userAccountModel = weakSelf.userAccountModel;
        [weakSelf.navigationController pushViewController:payVc animated:YES];
    };
    item3.accessoryType = XBSettingAccessoryTypeDisclosureIndicator;
    
    XBSettingSectionModel *section2 = [[XBSettingSectionModel alloc]init];
    section2.sectionHeaderName = @"支付";
    section2.sectionHeaderBgColor = SUB_TITLE_COLOR;
    section2.sectionHeaderHeight = 44;
    section2.itemArray = @[item2,item3];
    
    //************************************section3
    XBSettingItemModel *item4 = [[XBSettingItemModel alloc]init];
    item4.funcName = @"订单自动语音播报";
    item4.accessoryType = XBSettingAccessoryTypeSwitch;
    item4.switchValueChanged = ^(BOOL isOn)
    {
        if (isOn) {
            [YMSaveTool setBool:YES forKey:@"switchValueChanged"];
        }else{
           [YMSaveTool setBool:NO forKey:@"switchValueChanged"];
        }
    };
    XBSettingSectionModel *section3 = [[XBSettingSectionModel alloc]init];
    section3.sectionHeaderHeight = 44;
    section3.sectionHeaderBgColor = SUB_TITLE_COLOR;
    section3.sectionHeaderName = @"工具";
    section3.itemArray = @[item4];
    
    //************************************section4
    XBSettingItemModel *item5 = [[XBSettingItemModel alloc]init];
    item5.funcName = @"意见反馈";
    item5.accessoryType = XBSettingAccessoryTypeDisclosureIndicator;
    item5.executeCode = ^{
        [weakSelf.navigationController pushViewController:[[SYDFeedbackController alloc]init] animated:YES];
    };
    XBSettingItemModel *item6 = [[XBSettingItemModel alloc]init];
    item6.funcName = @"关于坐公交-车主";
    item6.executeCode = ^{
//        [weakSelf.navigationController pushViewController:[[SYDAboutViewController alloc]init] animated:YES];
        
        // 1.获取当前的StoryBoard面板
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        // 2.通过标识符找到对应的页面
        YMSetupViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"YMSetupViewController"];
        
        // 3.这里以push的方式加载控制器
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    item6.accessoryType = XBSettingAccessoryTypeDisclosureIndicator;
    
    XBSettingSectionModel *section4 = [[XBSettingSectionModel alloc]init];
    section4.sectionHeaderHeight = 44;
    section4.sectionHeaderName = @"关于";
    section4.sectionHeaderBgColor = SUB_TITLE_COLOR;
    section4.itemArray = @[item5,item6];
    
    if (self.userAccountModel.payCode.length > 0) {
        self.sectionArray = @[section1,section2,section3,section4];
    }else{
        self.sectionArray = @[section1,section3,section4];
    }
    
    [self.tableView reloadData];
    self.loginOutBtn.eventTimeInterval = 2.0;
    [[self.loginOutBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"退出登录");
        
        [[YMWebSocket sharedInstance] exit];
        // clear account 
        SYDAccount * account = [[SYDAccount alloc] init];
        [SYDAccountTool saveAccount:account];
        
        SYDLoginViewController *loginVc = [[SYDLoginViewController alloc]init];
        YMNavigationController *nav = [[YMNavigationController alloc]initWithRootViewController:loginVc];
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
       
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    XBSettingSectionModel *sectionModel = self.sectionArray[section];
    return sectionModel.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"setting";
    XBSettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    XBSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    
    XBSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[XBSettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.item = itemModel;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma - mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    XBSettingSectionModel *sectionModel = self.sectionArray[section];
    return sectionModel.sectionHeaderHeight;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    headerView.backgroundColor  = CONTENT_BG_COLOR;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, headerView.centerY - 7, 100, 14)];
    XBSettingSectionModel *sectionModel = self.sectionArray[section];
    label.text = sectionModel.sectionHeaderName;
    label.textColor = SUB_TITLE_COLOR;
    label.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:label];
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XBSettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    XBSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    if (itemModel.executeCode) {
        itemModel.executeCode();
    }
   
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    XBSettingSectionModel *sectionModel = [self.sectionArray firstObject];
    CGFloat sectionHeaderHeight = sectionModel.sectionHeaderHeight;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
#pragma mark---lazy
-(UITableView *)tableView{
    if (!_tableView) {
        if (iPhone8_X) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88 - 58) style:UITableViewStyleGrouped];
        } else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 48) style:UITableViewStyleGrouped];
        }
        _tableView.backgroundColor = CONTENT_BG_COLOR;
        _tableView.separatorColor = SEPARATE_LINE_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView drawBorderWithCornerRadius:5];
        _tableView.scrollEnabled = YES;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_tableView];
    }
    return  _tableView;
}

-(UIButton *)loginOutBtn{
    if (!_loginOutBtn) {
        _loginOutBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 58, SCREEN_WIDTH, 58)];
        [_loginOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [_loginOutBtn setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
        _loginOutBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _loginOutBtn.backgroundColor = GREEN_COLOR;
        [self.view addSubview:_loginOutBtn];
    }
    return _loginOutBtn;
}

-(UserAccountModel *)userAccountModel{
    if (!_userAccountModel) {
        _userAccountModel = [[UserAccountModel alloc]init];
    }
    return _userAccountModel;
}

@end


